import { Component, OnInit, OnDestroy } from '@angular/core';
import {  FormGroup, FormArray, FormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';
import { AuthService }            from '../../core/services/auth.service';
import { Store }                  from '@ngrx/store';
import { AppState }               from '../../interfaces';
import { Router, ActivatedRoute } from '@angular/router';
import { getAuthStatus }          from '../../auth/reducers/selectors';
import { Subscription }           from 'rxjs/Subscription';
import { ToasterService }         from '../../share/toastr/toastr.service';


@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.css']
})
export class RegisterComponent implements OnInit, OnDestroy {
  
  formSbumit =  false;
  signUpForm:   FormGroup;
  registerSubs: Subscription;
  returnUrl:    string;

  constructor(
    private fb:            FormBuilder,
    private store:         Store<AppState>,
    private router:        Router,
    private authService:   AuthService,
    public  toastrService: ToasterService,
    private route:         ActivatedRoute
  ) {
    // this.redirectIfUserLoggedIn();
  }

  ngOnInit() {
    this.initForm();
    console.log( 'ngOninit');
    // this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  }

  onSubmit() {
    const values    = this.signUpForm.value;
    const keys      = Object.keys(values);
    this.formSbumit = true;

    console.log('sing up form data ---', values);

    if (this.signUpForm.valid) {
      this.registerSubs = this.authService.register(values).subscribe(data => {
        // const errors = data.errors;
        // console.log('error message ---', errors);
        // if (errors) {
        //   keys.forEach(val => {
        //     if (errors[val]) { 
        //       this.pushErrorFor(val, errors[val][0]);
        //       console.log('print register component error ---', errors);
        //     }
        //   });
        // }
        console.log('successfuly !');
        this.router.navigate(['/auth/login']);
        this.toastrService.successfuly()
      },
      errors => {
        console.log('error --- ', errors);
        this.toastrService.errors('用户名已存在！');
      }
      );
      // this.toastrService.successful('create account successfuly ! ');
    }else {
      keys.forEach(val => {
        const ctrl = this.signUpForm.controls[val];
        if (!ctrl.valid) {
          this.pushErrorFor(val, null);
          ctrl.markAsTouched();
        }
      });
      this.toastrService.errors('create account failed ! ');
    }
  }

  private pushErrorFor(ctrl_name: string, msg: string) {
    this.signUpForm.controls[ctrl_name].setErrors({'msg': msg});
  }

  initForm() {

    this.signUpForm = this.fb.group({
      username: [ , Validators.required],
      email: [, Validators.compose([Validators.required, Validators.email])],
      password: [, Validators.compose([Validators.required, Validators.minLength(6)])],
      // confirm: [, Validators.compose([Validators.required, Validators.minLength(6)])] },
      // {validator: this.matchingPasswords('password', 'confirm')
    });
  }

  // redirectIfUserLoggedIn() {
  //   this.store.select(getAuthStatus).subscribe(
  //     data => {
  //       console.log('redirect to...');
  //       if (data === true) { 
  //         console.log('get Auth State');
  //         this.router.navigate(['/auth/login']);
  //         // this.router.navigate([this.returnUrl]);
  //         this.toastrService.successful('Create Account Successfuly !')
  //         console.log('register-->', data); 
  //       } 
  //     }
  //   );
  // }

  redirectLogin() {
    this.store.select(getAuthStatus).subscribe(
      data => {
        if (data === true) {
          console.log('request data ---', data);
          console.log('status ---', this.store.select(getAuthStatus));
          this.router.navigateByUrl('/auth/login');
        }
      }
      )
  }

  ngOnDestroy () {
    if (this.registerSubs) { this.registerSubs.unsubscribe(); }
  }

  matchingPasswords(passwordKey: string, confirmKey: string) {
    return (group: FormGroup): {[key: string]: any} => {
      const password = group.controls[passwordKey];
      const confirm = group.controls[confirmKey];
      if (password.value !== confirm.value) {
        return {
          mismatchedPasswords: true
        };
      }
    };
  }

}
